package org.zoomdev.zoom.common.utils;

import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.zoomdev.zoom.common.caster.Caster;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Page<T> {
    private List<T> list;
    private int pageSize;
    private int page;
    private int totalRows;

    public Page() {

    }


    public Page(List<T> list, int page, int pageSize, int totalRows) {
        this();
        this.list = list;
        this.page = page;
        this.pageSize = pageSize;
        this.totalRows = totalRows;
    }

    public static <T> Page<T> emptyPage() {
        List<T> list = Collections.emptyList();
        return new Page<T>(list, 1, 0, 0);
    }

    public <E> Page<E> convert(Class<E> classOfE) {
        Page page = new Page();
        page.page = this.page;
        page.pageSize = this.pageSize;
        page.totalRows = this.totalRows;
        if (this.list != null) {
            List<E> list = new ArrayList<>(this.list.size());
            for (int i = 0, c = this.list.size(); i < c; ++i) {
                T data = this.list.get(i);
                E r = Caster.to(data, classOfE);
                list.add(r);
            }
            page.setList(list);
        }
        return page;
    }

    public <E> Page<E> convert(Converter<T, E> converter) {
        Page page = new Page();
        page.page = this.page;
        page.pageSize = this.pageSize;
        page.totalRows = this.totalRows;
        if (this.list != null) {
            List<E> list = new ArrayList<>(this.list.size());
            for (int i = 0, c = this.list.size(); i < c; ++i) {
                T data = this.list.get(i);
                E r = converter.convert(data);
                list.add(r);
            }
            page.setList(list);
        }
        return page;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public int getLastPage() {
        if (pageSize == 0) return 1;
        if (totalRows % pageSize == 0) {
            return totalRows / pageSize;
        }
        return totalRows / pageSize + 1;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getTotalRows() {
        return totalRows;
    }

    public void setTotalRows(int totalRows) {
        this.totalRows = totalRows;
    }

    @Override
    public String toString() {
        return String.format("Page(page:%d,totalRows:%d,pageSize:%d,list:%s)", page, totalRows, pageSize, list);
    }


}
